<script lang="ts" setup>
import type { NotificationItem } from "@vben/layouts";

import { computed, ref, watch, onMounted } from "vue";

import { AuthenticationLoginExpiredModal } from "@vben/common-ui";
import { VBEN_DOC_URL, VBEN_GITHUB_URL } from "@vben/constants";
import { useWatermark } from "@vben/hooks";
import { BookOpenText, CircleHelp, MdiGithub, LogOut, Home } from "@vben/icons";
import { router } from "#/router";
import {
  BasicLayout,
  LockScreen,
  Notification,
  UserDropdown,
} from "@vben/layouts";
import { preferences } from "@vben/preferences";
import { useAccessStore, useUserStore } from "@vben/stores";
import { openWindow } from "@vben/utils";
import { ElMessageBox, ElMessage } from "element-plus";

import { $t } from "#/locales";
import { useAuthStore } from "#/store";
import LoginForm from "#/views/_core/authentication/login.vue";

const notifications = ref<NotificationItem[]>([
  {
    avatar: "https://avatar.vercel.sh/vercel.svg?text=VB",
    date: "3小时前",
    isRead: true,
    message: "描述信息描述信息描述信息",
    title: "收到了 14 份新周报",
  },
  {
    avatar: "https://avatar.vercel.sh/1",
    date: "刚刚",
    isRead: false,
    message: "描述信息描述信息描述信息",
    title: "朱偏右 回复了你",
  },
  {
    avatar: "https://avatar.vercel.sh/1",
    date: "2024-01-01",
    isRead: false,
    message: "描述信息描述信息描述信息",
    title: "曲丽丽 评论了你",
  },
  {
    avatar: "https://avatar.vercel.sh/satori",
    date: "1天前",
    isRead: false,
    message: "描述信息描述信息描述信息",
    title: "代办提醒",
  },
]);

const userStore = useUserStore();
const authStore = useAuthStore();
const accessStore = useAccessStore();
const { destroyWatermark, updateWatermark } = useWatermark();
const showDot = computed(() =>
  notifications.value.some((item) => !item.isRead)
);

const menus = computed(() => [
  {
    handler: () => {
      openWindow(VBEN_DOC_URL, {
        target: "_blank",
      });
    },
    icon: BookOpenText,
    text: $t("ui.widgets.document"),
  },
  {
    handler: () => {
      openWindow(VBEN_GITHUB_URL, {
        target: "_blank",
      });
    },
    icon: MdiGithub,
    text: "GitHub",
  },
  {
    handler: () => {
      openWindow(`${VBEN_GITHUB_URL}/issues`, {
        target: "_blank",
      });
    },
    icon: CircleHelp,
    text: $t("ui.widgets.qa"),
  },
]);

const avatar = computed(() => {
  return userStore.userInfo?.avatar ?? preferences.app.defaultAvatar;
});

const userName = computed(() => {
  return userStore.userInfo?.data?.userName ?? "admin";
});

async function handleLogout() {
  // 添加二次确认
  try {
    await ElMessageBox.confirm(`确定退出登录吗？`, "退出确认", {
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      beforeClose: async (action, instance, done) => {
        if (action === "confirm") {
          instance.confirmButtonLoading = true;
          try {
            await authStore.logout(false);
            done();
          } catch (error) {
            instance.confirmButtonLoading = false;
          }
        } else {
          done();
        }
      },
    });
    ElMessage.success("退出登录成功");
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`退出登录失败: ${error.message || "未知错误"}`);
      console.error("退出登录失败:", error);
    }
  }
}

function handleNoticeClear() {
  notifications.value = [];
}

function handleMakeAll() {
  notifications.value.forEach((item) => (item.isRead = true));
}
watch(
  () => preferences.app.watermark,
  async (enable) => {
    if (enable) {
      await updateWatermark({
        content: `${userStore.userInfo?.username} - ${userStore.userInfo?.realName}`,
      });
    } else {
      destroyWatermark();
    }
  },
  {
    immediate: true,
  }
);

function getTimeOfDay() {
  const now = new Date();
  const hours = now.getHours();

  if (hours >= 0 && hours < 12) {
    return "上午";
  } else if (hours >= 12 && hours < 18) {
    return "下午";
  } else {
    return "晚上";
  }
}

const goHome = async () => {
  let message = "是否返回导航页面？";
  try {
    ElMessageBox.confirm(message, "提示", {
      type: "success",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      beforeClose: async (action, instance, done) => {
        if (action === "confirm") {
          instance.confirmButtonLoading = true;
          try {
            await router.push({
              name: "SelectTest",
            });
            done();
          } catch (error) {
            instance.confirmButtonLoading = false;
            // 更全面的错误处理
            if (error === "cancel" || error?.message === "cancel") {
              // 用户取消，不显示错误
              return;
            }
          }
        } else {
          done();
        }
      },
    });
  } catch (error) {
    // 忽略取消操作的错误
    if (error !== "cancel") {
      ElMessage.error(`退出失败: ${error.message || "未知错误"}`);
      console.error("退出失败:", error);
    }
  }
};

const logoutButton = ref(null);

// 页面加载后给退出按钮添加脉冲动画
onMounted(() => {
  setTimeout(() => {
    const logoutBtn = document.querySelector(".mr-2.size-4");
    if (logoutBtn) {
      logoutBtn.classList.add("pulse");
    }
  }, 1000);
});
</script>

<template>
  <BasicLayout @clear-preferences-and-logout="handleLogout">
    <template #user-dropdown>
      <!-- 退出登录 -->
      <LogOut ref="logoutButton" class="mr-2 size-4" @click="handleLogout"
        style="margin-right: 24px; margin-left: 14px; cursor: pointer" />
      <!-- <UserDropdown
        :avatar
        :menus
        :text="userStore.userInfo?.realName"
        description="ann.vben@gmail.com"
        tag-text="Pro"
        @logout="handleLogout"
      /> -->
    </template>
    <template #notification>
      <div class="backHomeBtn" @click="goHome">
        <House class="home-icon" />
        返回导航
      </div>
      <div class="loginInfo flex items-center justify-center">
        <img :src="avatar" alt="" class="avatar" />
        <span>{{ getTimeOfDay() }}好，
          {{ userName }}
          ！</span>
      </div>
      <!-- 通知 -->
      <!-- <Notification
        :dot="showDot"
        :notifications="notifications"
        @clear="handleNoticeClear"
        @make-all="handleMakeAll"
      /> -->
    </template>
    <template #extra>
      <AuthenticationLoginExpiredModal v-model:open="accessStore.loginExpired" :avatar>
        <LoginForm />
      </AuthenticationLoginExpiredModal>
    </template>
    <template #lock-screen>
      <LockScreen :avatar @to-login="handleLogout" />
    </template>
  </BasicLayout>
</template>
<style scoped>
.backHomeBtn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 92px;
  height: 28px;
  margin: 0 24px;
  font-size: 12px;
  font-weight: 500;
  line-height: 28px;
  color: #2f69eb;
  background: #ffffff;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #2f69eb;
  position: relative;
  overflow: hidden;
}

.home-icon {
  margin-right: 4px;
  width: 16px;
  color: #2f69eb;
  transition: all 0.3s ease;
}

.backHomeBtn:hover {
  background: #2f69eb;
  color: #ffffff;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(47, 105, 235, 0.3);
}

.backHomeBtn:hover .home-icon {
  color: #fff;
  animation: bounce 0.6s ease;
}

.backHomeBtn:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(47, 105, 235, 0.3);
}

/* 退出按钮样式 */
.mr-2.size-4 {
  transition: all 0.3s ease;
  border-radius: 4px;
  padding: 2px;
}

.mr-2.size-4:hover {
  background-color: rgba(255, 255, 255, 0.2);
  transform: scale(1.1);
  color: #ff6b6b !important;
}

.mr-2.size-4:active {
  transform: scale(0.95);
}

.avatar {
  width: 24px;
  height: 24px;
  margin-right: 10px;
  border-radius: 50%;
}

.loginInfo {
  margin-right: 10px;
  font-size: 14px;
  font-weight: 400;
  color: #fff;
}

:deep(.logoBtn) {
  color: #000;
  display: none !important;
}

@keyframes bounce {

  0%,
  20%,
  50%,
  80%,
  100% {
    transform: translateY(0);
  }

  40% {
    transform: translateY(-3px);
  }

  60% {
    transform: translateY(-1px);
  }
}

/* 为退出按钮添加脉冲效果 */
@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(255, 107, 107, 0.4);
  }

  70% {
    box-shadow: 0 0 0 4px rgba(255, 107, 107, 0);
  }

  100% {
    box-shadow: 0 0 0 0 rgba(255, 107, 107, 0);
  }
}

.mr-2.size-4.pulse {
  animation: pulse 2s infinite;
}
</style>
